package com.beyondsoft.common.activiti.support;

import com.beyondsoft.common.activiti.exception.ActivitiException;
import com.beyondsoft.common.activiti.exception.ResultCode;
import com.beyondsoft.common.activiti.command.JumpTaskCmd;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.identity.Authentication;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zhangyan
 * @version $ Id: CompleteTaskSupport.java, v 0.1 2020/6/20 11:46 zhangyan Exp $
 */
@Component
@Slf4j
public class CompleteTaskSupport {

    @Resource
    private ProcessEngine processEngine;

    @Resource
    private ManagementService managementService;

    public void complete(String taskId, String procInsId, Map<String, Object> variables, String message, String assignee) {
        if (StringUtils.isBlank(taskId)) {
            throw new ActivitiException(ResultCode.NO_DATA.getCode(), "PCA完成任务失败，任务号不能为空CT002");
        }
        //添加审批意见
        if (StringUtils.isNotBlank(message)) {
            Authentication.setAuthenticatedUserId(assignee);//批注人的名称  一定要写，不然查看的时候不知道人物信息
            processEngine.getTaskService().addComment(taskId, procInsId, message);
        }
        if (CollectionUtils.isEmpty(variables)) {
            processEngine.getTaskService().complete(taskId);
            return;
        }
        processEngine.getTaskService().complete(taskId, variables);
    }

    /**
     * 跳转至指定活动节点
     *
     * @param taskId
     * @param toNodeId
     * @param message  审核意见
     * @throws Exception
     */
    public void executeCommand(String taskId, String toNodeId, String procInsId, String message, String assignee) {
        if (StringUtils.isNotBlank(message)
                && StringUtils.isNotBlank(procInsId)
                && StringUtils.isNotBlank(assignee)) {
            //批注人的名称  一定要写，不然查看的时候不知道人物信息
            Authentication.setAuthenticatedUserId(assignee);
            processEngine.getTaskService().addComment(taskId, procInsId, message);
        }
        managementService.executeCommand(new JumpTaskCmd(taskId, toNodeId));
    }

}
